package com.example.strategy;

import HslCommunication.Core.Types.OperateResultExOne;
import HslCommunication.Profinet.Siemens.SiemensS7Net;
import com.example.entity.DbBlock;
import com.example.enums.TypeEnum;
import com.example.exception.OpcException;
import com.example.s7.PLCUtils;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Component;

/**
 * Copyright: Copyright (c) 2022
 *
 * <p>
 * Description: PLC二进制变量数据进行转换
 *
 * @author LiuFeng
 * @version 2022/11/14 10:23
 * @since
 */
@Component
@Slf4j
public class BinaryDataConvertStrategy implements PLCDataConvertStrategy {

    @Override
    public String convert(DbBlock dbBlock) {
//        String group = handleGroup(dbBlock);
//        byte[] data;
        OperateResultExOne<Byte> result;
        SiemensS7Net siemensS7Net = null;
        String offset = null;
        try {
            siemensS7Net = getConnect();
            if (dbBlock.getCGroup() == null || dbBlock.getCGroup().equalsIgnoreCase("DIO")
                    || dbBlock.getAddrParams().contains("I")
            ) {
//            data = PLCUtils.readPlcData(dbBlock.getAddrParams(), (short) 1L);
//            String str = PLCUtils.getBinaryStrFromByte(data[0]);
                result = siemensS7Net
                        .ReadByte(dbBlock.getAddrParams());
            } else {
//            data = PLCUtils.readPlcData("D"+offset, (short) 1L);
//            String str = PLCUtils.getBinaryStrFromByte(data[0]);
//            System.out.println(str);
//            data = PLCUtils.readPlcData(DaveArea.DB, Integer.parseInt(group), dbBlock.getLength(), Integer.parseInt(offset));
//
//            BitConverter bitConverter = new BitConverter();
//            Boolean value = bitConverter.extract(Boolean.class, data, 0, 0);
//
                offset = handleOffset(dbBlock);

                //读取数据
                result = siemensS7Net
                        .ReadByte(offset);
            }
            if (result.IsSuccess) {
                String str = PLCUtils.getBinaryStrFromByte(result.Content);
                return str;
            } else {
                log.error("读取数据失败，DB地址是：{}，buffer地址是：{}，错误原因是：{}", dbBlock.getAddrParams(), offset, result.Message);
                return null;
            }
        } catch (Exception ex) {
            log.error("读取：{}，数据异常：{}", dbBlock.getName(), ex.getMessage());
            throw new OpcException(ex);
        } finally {
            returnConnect(siemensS7Net);
        }
    }

    @Override
    public String getType() {
        return TypeEnum.BINARY.getType();
    }
}
